package cn.iocoder.yudao.module.agent.controller.admin.user;

import cn.iocoder.yudao.module.agent.base.MemberRespVO;
import cn.iocoder.yudao.module.agent.controller.admin.withdrawaccount.vo.AgentWithdrawAccountRespVO;
import cn.iocoder.yudao.module.agent.convert.base.AgentConvert;
import cn.iocoder.yudao.module.agent.convert.withdrawaccount.AgentWithdrawAccountConvert;
import cn.iocoder.yudao.module.agent.dal.dataobject.withdrawaccount.AgentWithdrawAccountDO;
import cn.iocoder.yudao.module.agent.service.withdrawaccount.AgentWithdrawAccountService;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.AppAuthSmsSendReqVO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.sms.SmsSendApi;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeValidateReqDTO;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.agent.controller.admin.user.vo.*;
import cn.iocoder.yudao.module.agent.dal.dataobject.user.AgentUserDO;
import cn.iocoder.yudao.module.agent.convert.user.AgentUserConvert;
import cn.iocoder.yudao.module.agent.service.user.AgentUserService;

@Tag(name = "管理后台 - 代理人")
@RestController
@RequestMapping("/agent/user")
@Validated
public class AgentUserController {

    @Resource
    private AgentUserService userService;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private AgentWithdrawAccountService withdrawAccountService;

    @Resource
    private SmsCodeApi smsCodeApi;


    @PostMapping("/create")
    @Operation(summary = "创建代理人")
    @PreAuthorize("@ss.hasPermission('agent:user:create')")
    public CommonResult<Long> createUser(@Valid @RequestBody AgentUserCreateReqVO createReqVO) {
        return success(userService.createUser(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新代理人")
    @PreAuthorize("@ss.hasPermission('agent:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody AgentUserUpdateReqVO updateReqVO) {
        userService.updateUser(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除代理人")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('agent:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得代理人")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('agent:user:query')")
    public CommonResult<AgentUserRespVO> getUser(@RequestParam("id") Long id) {
        AgentUserDO user = userService.getUser(id);
        return success(AgentUserConvert.INSTANCE.convert(user));
    }

    @GetMapping("/userId")
    @Operation(summary = "获得代理人")
    @Parameter(name = "userId", description = "会员id", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('agent:user:query')")
    public CommonResult<AgentUserRespVO> getByUserId(@RequestParam("userId") Long userId) {
        AgentUserDO agentUserDO = userService.getByUserId(userId);
        if(agentUserDO == null){
            return success(null);
        }

        MemberUserRespDTO memberUserRespDTO = memberUserApi.getUser(agentUserDO.getUserId());
        MemberRespVO memberRespVO = AgentConvert.INSTANCE.covnertMember(memberUserRespDTO);

        AgentWithdrawAccountDO accountDO = withdrawAccountService.getWithdrawAccount(agentUserDO.getWithdrawId());
        AgentWithdrawAccountRespVO accountRespVO = AgentWithdrawAccountConvert.INSTANCE.convert(accountDO);

        return success(AgentUserConvert.INSTANCE.convert02(agentUserDO, memberRespVO, accountRespVO));
    }

    @GetMapping("/list")
    @Operation(summary = "获得代理人列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('agent:user:query')")
    public CommonResult<List<AgentUserRespVO>> getUserList(@RequestParam("ids") Collection<Long> ids) {
        List<AgentUserDO> list = userService.getUserList(ids);
        return success(AgentUserConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得代理人分页")
    @PreAuthorize("@ss.hasPermission('agent:user:query')")
    public CommonResult<PageResult<AgentUserRespVO>> getUserPage(@Valid AgentUserPageReqVO pageVO) {
        PageResult<AgentUserDO> pageResult = userService.getUserPage(pageVO);

        // 查询用户信息
        Set<Long> memberIds = convertSet(pageResult.getList(), AgentUserDO::getUserId);
        Map<Long, MemberUserRespDTO> memberMap = memberUserApi.getUserMap(memberIds);

        List<AgentWithdrawAccountDO> accountList = withdrawAccountService.getWithdrawAccountListByUserIds(memberIds);
        Map<Long, AgentWithdrawAccountDO> accountMap = convertMap(accountList, AgentWithdrawAccountDO::getUserId);

        return success(AgentUserConvert.INSTANCE.convertPage02(pageResult, memberMap, accountMap));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出代理人 Excel")
    @PreAuthorize("@ss.hasPermission('agent:user:export')")
    @OperateLog(type = EXPORT)
    public void exportUserExcel(@Valid AgentUserExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<AgentUserDO> list = userService.getUserList(exportReqVO);
        // 导出 Excel
        List<AgentUserExcelVO> datas = AgentUserConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "代理人.xls", "数据", AgentUserExcelVO.class, datas);
    }

    @PostMapping("/send-sms-code")
    @Operation(summary = "绑定分销员发送手机验证码")
    public CommonResult<Boolean> sendSmsCode(@RequestBody @Valid AgentBindSmsSendReqVO reqVO) {
        return success(userService.sendSmsCode(reqVO));
    }

    @PostMapping("bind-brokerage")
    @Operation(summary = "绑定分销人员")
    public CommonResult<Boolean> bindBrokerageUser(@RequestBody @Valid AgentBindBrokerageReqVO reqVO){
        return success(userService.bindBrokerageUser(reqVO));
    }

}
